import React from "react";
import Select from 'antd/lib/select';
import Button from 'antd/lib/button';
import Tree from 'antd/lib/tree';
import Modal from 'antd/lib/modal';
import Dropdown from 'antd/lib/dropdown';
import Menu from 'antd/lib/menu';
import 'antd/dist/antd.less';
import { get } from "lodash";

import routeWithUserSession from "@/components/ApplicationArea/routeWithUserSession";
import PageHeader from "@/components/PageHeader";
import CreateItemDialog from "@/components/enums/CreateItemDialog";
import CreateEnumsDialog from "@/components/enums/CreateEnumsDialog";
import navigateTo from "@/components/ApplicationArea/navigateTo";
import Enums from "@/services/enums";
import notification from "@/services/notification";
import "./EnumsList.less";
import routes from "@/services/routes";
import { WarningOutlined, SecurityScanTwoTone, DownOutlined } from "@ant-design/icons";
const { confirm } = Modal;

class EnumsList extends React.Component {
  state = {
    loading: true,
    enum_code: '',
    enums: [],
    gData: [],
    isChanged: false,
    selectedKeys: [],
    selectedTitle: '',
  };

  componentWillMount() {
    this.loadEnums();
  };

  loadEnums() {
    Enums.all().then(data => {
      this.setState({
        enums: data,
      });
      this.loadData(data[0].code);
    });
  }

  loadData(enum_code = this.state.enum_code) {
    Enums.items(enum_code).then(data => {
      this.setState({
        loading: false,
        enum_code: enum_code,
        gData: data,
        isChanged: false,
        selectedKeys: [],
        selectedTitle: '',
      });
    });
  }

  onDragEnter = info => {
    window.console.log(info);
  };

  onDrop = info => {
    const dropKey = info.node.props.eventKey;
    const dragKey = info.dragNode.props.eventKey;
    const dropPos = info.node.props.pos.split('-');
    const dropPosition = info.dropPosition - Number(dropPos[dropPos.length - 1]);

    const loop = (data, key, callback) => {
      data.forEach((item, index, arr) => {
        if (item.key === key) {
          return callback(item, index, arr);
        }
        if (item.children) {
          return loop(item.children, key, callback);
        }
      });
    };
    const data = [...this.state.gData];

    // Find dragObject
    let dragObj;
    loop(data, dragKey, (item, index, arr) => {
      arr.splice(index, 1);
      dragObj = item;
    });

    if (!info.dropToGap) {
      // Drop on the content
      loop(data, dropKey, item => {
        item.children = item.children || [];
        // where to insert 示例添加到尾部，可以是随意位置
        item.children.push(dragObj);
      });
    } else if (
      (info.node.props.children || []).length > 0 && // Has children
      info.node.props.expanded && // Is expanded
      dropPosition === 1 // On the bottom gap
    ) {
      loop(data, dropKey, item => {
        item.children = item.children || [];
        // where to insert 示例添加到头部，可以是随意位置
        item.children.unshift(dragObj);
      });
    } else {
      let ar;
      let i;
      loop(data, dropKey, (item, index, arr) => {
        ar = arr;
        i = index;
      });
      if (dropPosition === -1) {
        ar.splice(i, 0, dragObj);
      } else {
        ar.splice(i + 1, 0, dragObj);
      }
    }

    this.setState({
      gData: data,
      isChanged: true,
    });
  };

  onSelect = (selectedKeys, e) => {
    this.setState({
      selectedKeys: selectedKeys,
      selectedTitle: e.node.props.title,
    });
  };

  handleSave = () => {
    const loop = (das, index) => {
      let items = [];
      das.forEach((item) => {
        item.icon = "";
        if (item.children) {
          item.children = loop(item.children, index + 1);
        }
        items.push(item);
      });
      return items;
    };
    let datas = loop(this.state.gData, 0);
    Enums.save(this.state.enum_code, datas).then(() => {
      notification.success("枚举值保存成功。");
      this.setState({
        isChanged: false,
      });
    });
  }

  showCreateItemDialog = () => {
    CreateItemDialog.showModal({key:"",label:"",children:[]})
      .onClose((result = {}) => {
        // if (Enums.existItemByKey(this.state.gData, result.key)) {
        //   notification.error(`代码${result.key}已经存在，不能重复！`);
        //   return;
        // }

        let data = [...this.state.gData];
        data.push(result);
        this.setState({
          gData: data,
          isChanged: true,
        });
      }).onDismiss(() => {
        navigateTo("enums", true);
      });
  };
  // removeItemByKey(items, key)
  // {
  //   for (var item in items) {
  //     if (items[item].key === key) {
  //       items.splice(item, 1);
  //       break;
  //     }
  //     if (item.hasOwnProperty("children")) {
  //       const r = removeItemByKey(item, key);
  //       items.splice(item, 1, r)
  //       if (r.length !== item.length) break;
  //     }
  //   }
  //   return items;
  // }

  showEditItemDialog = () => {
    if (this.state.selectedKeys.length !== 1) {
      notification.error("请选择枚举项！");
      return;
    }
    const loop = (items,keys) => {
        for (var item in items) {
          if (items[item].key === keys) {
            return items[item];
          }
          if (items[item].hasOwnProperty("children")) {
            let item2=items[item]["children"];
            for (var its in item2) {
              if (item2[its].key === keys) {
                return item2[its];
              }
              if (item2[its].hasOwnProperty("children")) {
                let item3=item2[its]["children"];
                for (var it3 in item3) {
                  if (item3[it3].key === keys) {
                    return item3[it3];
                  }
                  if (item3[it3].hasOwnProperty("children")) {
                    let item4=item3[it3]["children"];
                    for (var it4 in item4) {
                      if (item4[it4].key === keys) {
                        return item4[it4];
                      }
                    }
                  }
                }
              }
            }
          }
        }
        return {key:""};
    }
    let keys=this.state.selectedKeys[0];
    let keyrow=loop(this.state.gData,keys)
    if(keyrow.key===""){
      notification.error(`级次太深，不能编辑！`);
      return;
    }
    CreateItemDialog.showModal(keyrow)
      .onClose((result = {}) => {
        let items=this.state.gData;
        // if (Enums.existItemByKey(items, result.key)) {
        //   notification.error(`代码${result.key}已经存在，不能重复！`);
        //   return;
        // }
        for (var item in items) {
          if (items[item].key === keys) {
            items[item] =result;
            break;
          }
          if (items[item].hasOwnProperty("children")) {
            let item2=items[item]["children"];
            for (var its in item2) {
              if (item2[its].key === keys) {
                 item2[its]=result;
                 break;
              }
              if (item2[its].hasOwnProperty("children")) {
                let item3=item2[its]["children"];
                for (var it3 in item3) {
                  if (item3[it3].key === keys) {
                    item3[it3]=result;
                    break;
                  }
                  if (item3[it3].hasOwnProperty("children")) {
                    let item4=item3[it3]["children"];
                    for (var it4 in item4) {
                      if (item4[it4].key === keys) {
                        item4[it4]=result;
                        break;
                      }
                    }
                  }
                }
              }
            }
          }
        }
        this.setState({
          gData: items,
          isChanged: true,
        });
      }).onDismiss(() => {
        navigateTo("enums", true);
      });
  };
  showCreateEnumsDialog = () => {
    CreateEnumsDialog.showModal()
      .onClose((result = {}) => {
        if (result.success) {
          this.loadEnums();
        }
      }).onDismiss(() => {
        navigateTo("enums", true);
      });
  };

  handleDeleteItem = () => {
    if (this.state.selectedKeys.length !== 1) {
      notification.error("请选择枚举项！");
      return;
    }
    confirm({
      title: `确定删除枚举值“${this.state.selectedTitle}”吗？`,
      icon: <WarningOutlined />,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        let items = this.state.gData;
        let keys=this.state.selectedKeys[0];
        for (var item in items) {
          if (items[item].key === keys) {
            items.splice(item, 1);
            break;
          }
          if (items[item].hasOwnProperty("children")) {
            let item2=items[item]["children"];
            for (var its in item2) {
              if (item2[its].key === keys) {
                 item2.splice(its, 1);
                 break;
              }
              if (item2[its].hasOwnProperty("children")) {
                let item3=item2[its]["children"];
                for (var it3 in item3) {
                  if (item3[it3].key === keys) {
                    item3.splice(it3, 1);
                    break;
                  }
                  if (item3[it3].hasOwnProperty("children")) {
                    let item4=item3[it3]["children"];
                    for (var it4 in item4) {
                      if (item4[it4].key === keys) {
                        item4.splice(it4, 1);
                        break;
                      }
                    }
                  }
                }
              }
            }
          }
        }
        this.setState({
          gData: items,
          isChanged: true,
        });
        notification.success("枚举值删除成功！");
      },
    });
  };

  handleDelete = () => {
    if (Enums.getEnumsIsBuiltinByCode(this.state.enums, this.state.enum_code)) {
      notification.error("系统预设枚举类型不能删除！");
      return;
    }

    confirm({
      title: `确定删除枚举类型“${Enums.getEnumsNameByCode(this.state.enums, this.state.enum_code)}”吗？该操作将删除枚举类型和其下的全部枚举值。`,
      icon: <WarningOutlined />,
      okText: '确定',
      okType: 'danger',
      cancelText: '取消',
      onOk: () => {
        Enums.delete(this.state.enum_code).then(() => {
          notification.success("枚举类型删除成功！");
          this.loadEnums();
        }).catch(error => {
          notification.error(get(error, "response.data.message", "删除失败！"));
        });
      },
    });
  };

  selectChange = (value) => {
    this.loadData(value);
  };

  renderSelect() {
    return (
      <Select style={{ width: 200 }} defaultValue={this.state.enum_code} onChange={this.selectChange}>
        {this.state.enums.map(item => (
          <option value={item.code}>{item.is_builtin ? '[' + item.name + ']' : item.name}</option>
        ))}
      </Select>
    );
  };

  render() {
    if (this.state.loading || this.state.enums.length === 0) return null;
    const loop = (das, index) => {
      let items = [];
      das.forEach((item) => {
        item.icon = <SecurityScanTwoTone />;
        if (item.children) {
          item.children = loop(item.children, index + 1);
        }
        items.push(item);
      });
      return items;
    };
    let datas =loop(this.state.gData, 0);
    return (
      <div className="settings-screen">
        <div className="container">
          <PageHeader title="枚举设置" />
          <div className="bg-white tiled">
            <Button type="primary" onClick={this.handleSave} disabled={!this.state.isChanged}>
              <i className="fa fa-save m-r-5" />
              保存
            </Button>
            <Dropdown
              trigger={["click"]}
              overlay={
                <Menu>
                  <Menu.Item key="new-item">
                    <a onMouseUp={this.showCreateItemDialog}>新建</a>
                  </Menu.Item>
                  <Menu.Divider />
                  <Menu.Item key="new-item">
                    <a onMouseUp={this.showEditItemDialog}>编辑</a>
                  </Menu.Item>
                  <Menu.Divider />
                  <Menu.Item key="delete-item">
                    <a onMouseUp={this.handleDeleteItem}>删除</a>
                  </Menu.Item>
                </Menu>
              }>
              <Button type="primary" data-test="CreateButton">
                枚举项 <DownOutlined />
              </Button>
            </Dropdown>
            <label>枚举类型：
              {this.renderSelect()}</label>
            <Dropdown
              trigger={["click"]}
              overlay={
                <Menu>
                  <Menu.Item key="new-enums">
                    <a onMouseUp={this.showCreateEnumsDialog}>新建</a>
                  </Menu.Item>
                  <Menu.Divider />
                  <Menu.Item key="delete-enums">
                    <a onMouseUp={this.handleDelete}>删除</a>
                  </Menu.Item>
                </Menu>
              }>
              <Button type="primary" data-test="CreateButton">
                枚举类型 <DownOutlined />
              </Button>
            </Dropdown>
          </div>
          <div className="p-15">
            <Tree
              className="draggable-tree"
              draggable
              blockNode
              showIcon
              // showLine
              switcherIcon={<DownOutlined />}
              defaultExpandAll
              onDragEnter={this.onDragEnter}
              onDrop={this.onDrop}
              onSelect={this.onSelect}
              treeData={datas}
            />
          </div>
        </div>
      </div>
    );
  }
}

routes.register(
  "Enums.List",
  routeWithUserSession({
    path: "/enums",
    title: "枚举设置",
    render: pageProps => <EnumsList {...pageProps} />,
  })
);
// export default [
//   routeWithUserSession({
//     path: "/enums",
//     title: "枚举设置",
//     render: pageProps => <EnumsList {...pageProps} />,
//   }),
// ];
